package win.liumian.sso.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import static win.liumian.sso.util.Constants.BEIJING_TIMEZONE_OF_GMT;

/**
 * @author liumian
 */
public class CookieUtil {


    /**
     * 销毁cookie
     *
     * @param response
     * @param cookieName cookie名
     * @param domain     cookie 所属的domain 必须设置，否则删除不成功
     */
    public static void destroyCookie(HttpServletResponse response,
                                     String cookieName,
                                     String domain) {
        Cookie cookie = new Cookie(cookieName, "");
        cookie.setDomain(domain);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }


    /**
     * 生成cookie并添加到response中
     *
     * @param response
     * @param cookieName  cookie 名
     * @param cookieValue cookie值
     * @param expiredTime 过期时间，自动加上东八区的时差
     * @param domain      域名
     */
    public static void genCookie4Response(HttpServletResponse response,
                                          String cookieName,
                                          String cookieValue,
                                          int expiredTime,
                                          String domain) {

        Cookie cookie = new Cookie(cookieName, cookieValue);
        cookie.setMaxAge(expiredTime + BEIJING_TIMEZONE_OF_GMT);
        cookie.setDomain(domain);
        cookie.setPath("/");
        response.addCookie(cookie);

    }
}
